#include <Arduino.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <HTTPClient.h>

#define SSID        ""   // your SSID
#define PASS        ""   // your PSWD

uint32_t timer3;

// 20230909 增加Epoch time获取接口
// get current local time, lib and define
#include "time.h" 
const char* ntpServer = "pool.ntp.org";
const long  gmtOffset_sec      = 3600 * 8;       // 8 Hours
const int   daylightOffset_sec = 3600 * 0;       // no daylight offset
// get current local time, function
time_t getEpochTime()
{
  struct tm timeinfo;
  if (!getLocalTime(&timeinfo)) {
    Serial.println("Failed to obtain time.");
    return 0;
  }

  time_t epochTime;
  time(&epochTime);
  Serial.print("Epoch Time: "); Serial.print(epochTime);
  Serial.println(&timeinfo, "  %A, %B %d %Y %H:%M:%S");
  return epochTime;
}

// 20230909 增加百度鹰眼轨迹上传功能，HTTP POST API接口
// POST: https://yingyan.baidu.com/api/v3/track/addpoint
/*
    "ak",XXXX                       // your ak
    "service_id",237918             // your service_id
    "entity_name","BA7MZO"
    "latitude",21.276161            // 纬度  XX.XXXX Degree
    "longitude",110.359064          // 经度 XXX.XXXX Degree
    "loc_time",loc_time             // 定位时间戳，精确到秒
    "coord_type_input","wgs84"      // 坐标，wgs84：GPS坐标， gcj02：国测局加密坐标， bd09ll：百度经纬度坐标
    "speed",10.23                   // 速度，单位：km/h
    "direction",15                  // 方向，取值规则： 范围为[0,359]，0度为正北方向，顺时针
*/
String makePostPayload(time_t epochTime, float lat, float lon, float speed, float angle)
{
  // 将GPS模块经纬度转换为degree
  float temp;
  float tempLat = int(lat / 100.0);
  temp = lat - tempLat * 100;
  tempLat = tempLat + temp / 60.0;

  float tempLon = int(lon / 100.0);
  temp = lon - tempLon * 100;
  tempLon = tempLon + temp / 60.0;

  String payload = "ak=your_ak&service_id=237918&entity_name=BA7MZO"; // change to your ak
  payload += "&loc_time=";
  payload += String(epochTime);
  payload += "&latitude=";

  payload += String(tempLat, 6);      // 保留6位小数
  payload += "&longitude=";
  payload += String(tempLon, 6);      // 保留6位小数
  payload += "&speed=";
  payload += String(speed);
  payload += "&direction=";
  payload += String(int(angle));
  payload += "&coord_type_input=wgs84";

  Serial.println(payload.c_str());
  return payload;
}

// 20230909 增加百度鹰眼轨迹上传功能，HTTP POST API接口
void addpointYingyan()
{
  // wait for WiFi connection
  if ((WiFi.status() == WL_CONNECTED))
  {
    time_t epochTime = getEpochTime();
    String payloadPost = makePostPayload(epochTime,2254.8190,11393.4042,100,120); // Lat/Lon from GPS Module, just for test

    HTTPClient http;
    WiFiClient client;

    // configure traged server and url
    http.begin(client, "http://yingyan.baidu.com/api/v3/track/addpoint");
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");

    Serial.print("[HTTP] POST...\n");
    // start connection and send HTTP header and body
    int httpCode = http.POST(payloadPost);
    // httpCode will be negative on error
    if (httpCode > 0)
    {
      // HTTP header has been send and Server response header has been handled
      Serial.printf("[HTTP] POST... code: %d\n", httpCode);

      // file found at server
      if (httpCode == HTTP_CODE_OK)
      {
        const String& payload = http.getString();
        Serial.println("received payload:\n<<");
        Serial.println(payload);
        Serial.println(">>");
      }
    }
    else
    {
      Serial.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str());
    }

    http.end();
  }
}

void setup()
{
  Serial.begin(115200);
  Serial.print("\r\nAPRS Track with ESP32C3 from LuatOS... ver ");
  Serial.print(__DATE__); Serial.print(" "); Serial.println(__TIME__);
  
  Serial.println("\r\nStarting ...");
  WiFi.begin(SSID, PASS);
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(1000);
  }

  Serial.println("");
  Serial.print("Connected to "); Serial.print(SSID); Serial.print(", IP: "); Serial.println(WiFi.localIP());
  timer3 = millis();

  // get current local time, configure the NTP server
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
  while (0 == getEpochTime())
  {
    delay(2000);
  }
}

void loop()
{
  // Connect to Baidu Yingyan
  if ((millis() - timer3) > 120000)
  {
    timer3 = millis(); // reset the timer3
    addpointYingyan();
  }

  delay(2000);
}
